package controllers

import (
	"fmt"
	"goseckill/common"
	"goseckill/models"
	"goseckill/service"
	"strconv"

	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"github.com/kataras/iris/v12/sessions"
)

type UserController struct {
	Ctx iris.Context
	Service service.IUserService
	// session 会话  保留登录状态等等
	Session *sessions.Session
}

func (c *UserController) GetRegister() mvc.View {
	return mvc.View{
		Name: "user/register.html",
	}
}


// 注册
func (c *UserController) PostRegister() {
	// 拿到注册页面的表单数据
	// 根据model
	// type User struct {
	// 	ID           int64  `json:"id" form:"ID" sql:"ID"`
	// 	NickName     string `json:"nickName" form:"nickName" sql:"nickName"`
	// 	UserName     string `json:"userName" form:"userName" sql:"userName"`
	// 	HashPassword string `json:"-" form:"passWord" sql:"passWord"`
	// }
	var (
		nickName = c.Ctx.FormValue("nickName")
		userName = c.Ctx.FormValue("userName")
		passWord = c.Ctx.FormValue("passWord")
	)
	// 验证表单
	user := &models.User{
		UserName: userName,
		NickName: nickName,
		HashPassword: passWord,
	}
	// 读数据库
	_,err := c.Service.AddUser(user)
	c.Ctx.Application().Logger().Debug(err)
	if err!=nil {
		c.Ctx.Redirect("/user/error")
		return 
	}

	c.Ctx.Redirect("/user/login")
}
func (u *UserController) GetLogin() mvc.View {
	return mvc.View{
		Name: "user/login.html",
	}
}
// 登录 Post-更新操作
func (u *UserController ) PostLogin() mvc.Response{
	var (
		userName = u.Ctx.FormValue("userName")
		passWord = u.Ctx.FormValue("passWord")
	)
	// 验证
	// 1 对明文密码加密 2 验证
	user,isOk := u.Service.IsPwdSuccess(userName,passWord)
	if !isOk {
		// 重复
		return mvc.Response{
			Path:"/user/login",
		}
	}
	//登录成功
	// 写入Cookie    Cookie由服务器发送，客户端保存在浏览器中
	// 存入key-v  uid-ID
	common.SetGlobalCookie(u.Ctx, "uid", strconv.FormatInt(user.ID, 10))
	// 登录状态
	uidByte := []byte(strconv.FormatInt(user.ID,10))
	// 加密信息写入
	uidString,err := common.EnPwdCode(uidByte)
	if err!=nil{
		fmt.Println(err)
	}
	common.SetGlobalCookie(u.Ctx, "sign", uidString)   // 签名
	return mvc.Response{
		Path: "/product/",
	}
}

